<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entity_Category_Collection extends Core_Db_Collection {

	protected $_excludeCatId = null;

	public function addPostCount() {
		$this->getSelect()
			->setPart(Core_Db_Select::COLUMNS, array('category.*, count(p.id) as post_count'))
			->joinLeft('post p', 'category.id = p.category')
			->group('category.id');
		return $this;
	}
	
	public function setExcludeCategoryId($catId) {
		$this->_excludeCatId = $catId;
		return $this;
	}
	
	public function sortByGroup($excludeId=null) {
		$tam = array();
		$this->_prepareData();
		$this->_collectItems(null, $tam);
		$this->_items = $tam;
		return $this;
	}
	
	public function addParentCategoryFilter($id) {
		$this->getSelect()->where("parent_category = $id");
		return $this;
	}
	
	protected function _prepareData() {
		$this->getSelect()->order('sort_order');
		parent::_prepareData();
	}
	
	protected function _collectItems($pId, &$arr, $level=0) {
		foreach($this->_items as $item) {
			if ($item['parent_category'] == $pId && $this->_excludeCatId != $item['id']) {
				$item['level'] = $level;
				array_push($arr, $item);
				$this->_collectItems($item['id'], $arr, $level+1);
			}
		}
	}
}